<?php declare(strict_types=1);

namespace App\Http\Business\Admin;

use App\Model\SystemRole;
use App\Model\SystemRolePermissions;
use App\Model\SystemMenu;


/**
 * 系统角色-业务类
 * Class SystemRoleBusiness
 * @package App\Http\Business\Admin
 */
class SystemRoleBusiness
{
        /**
         * 查询角色
         * @param string $roleId
         * @return array
         */
        public static function query(string $roleId): array
        {
                if ($roleId) {
                        $arrField = ['roleId', 'name', 'status', 'sort'];
                        $arrResult = SystemRole::primaryKeyFind(strAddslashes($roleId), $arrField);
                } else {
                        $arrParam = get();
                        $intPage = intval(issetArrKey($arrParam, 'page', 1));
                        $intLimit = intval(issetArrKey($arrParam, 'limit', 10));
                        $arrWhere = [];
                        if (isset($arrParam['name']) && $arrParam['name']) $arrWhere[] = ['name', 'like', "%{$arrParam['name']}%"];
                        if (isset($arrParam['createTime']) && $arrParam['createTime']) $arrWhere[] = ['whereBetween', 'createTime', array_map('strtotime', $arrParam['createTime'])];
                        if (isset($arrParam['updateTime']) && $arrParam['updateTime']) $arrWhere[] = ['whereBetween', 'updateTime', array_map('strtotime', $arrParam['updateTime'])];
                        if (isset($arrParam['status']) && $arrParam['status']) $arrWhere['status'] = intval($arrParam['status']);
                        $arrField = ['roleId', 'name', 'status', 'sort', 'createTime', 'updateTime'];
                        $arrOrderBy = ['sort' => 'DESC', 'createTime' => 'DESC'];
                        $arrResult = SystemRole::getList($arrWhere, $arrField, $intPage, $intLimit, $arrOrderBy);
                        $arrResult['page'] = $intPage;
                        $arrResult['limit'] = $intLimit;
                }
                return callbackParam(0, true, $arrResult);
        }

        /**
         * 新增角色
         * @return array
         * @throws \Exception
         */
        public static function add(): array
        {
                $arrParam = post();
                $strRoleId = uuid();
                $arrSet = [
                        'roleId' => $strRoleId,
                        'name' => strAddslashes($arrParam['name']),
                        'sort' => intval(issetArrKey($arrParam, 'sort', 1)),
                        'status' => intval($arrParam['status']),
                        'createTime' => request()->timestamp
                ];
                $bool = SystemRole::insert($arrSet);
                if (!$bool) throw new \Exception('服务器处理数据失败');
                $arrSystemLogData = ['behavior' => '新增角色', 'operationAfter' => $arrSet];
                setSystemLog($arrSystemLogData);
                $arrResult = ['roleId' => $strRoleId];
                return callbackParam(0, true, $arrResult, '新增成功');
        }

        /**
         * 编辑角色
         * @param string $roleId
         * @return array
         * @throws \Exception
         */
        public static function edit(string $roleId): array
        {
                $arrParam = post();
                $arrOperationBefore = self::query($roleId)['data'];
                if (!$arrOperationBefore) throw new \Exception('数据不存在');
                $arrWhere = ['roleId' => strAddslashes($roleId)];
                $arrSet = [
                        'name' => strAddslashes($arrParam['name']),
                        'sort' => intval(issetArrKey($arrParam, 'sort', 1)),
                        'status' => intval($arrParam['status']),
                        'updateTime' => request()->timestamp
                ];
                $bool = SystemRole::renewal($arrWhere, $arrSet);
                if (!$bool) throw new \Exception('服务器处理数据失败');
                $arrSystemLogData = ['behavior' => '编辑角色', 'operationBefore' => $arrOperationBefore, 'operationAfter' => $arrSet, 'whereData' => $arrWhere];
                setSystemLog($arrSystemLogData);
                return callbackParam(0, true, [], '编辑成功');
        }

        /**
         * 编辑指定字段
         * @param string $roleId
         * @param string $field
         * @return array
         * @throws \Exception
         */
        public static function editSpecifiedField(string $roleId, string $field): array
        {
                $arrOperationBefore = SystemRole::primaryKeyFind(strAddslashes($roleId), [strAddslashes($field)]);
                if (!$arrOperationBefore) throw new \Exception('数据不存在');
                switch ($field) {
                        case 'status':
                                $arrSet = ['status' => intval(post('status'))];
                                break;
                        default :
                                throw new \Exception('未知字段');
                }
                $arrWhere = ['roleId' => $roleId];
                $arrSet['updateTime'] = request()->timestamp;
                $bool = SystemRole::renewal($arrWhere, $arrSet);
                if (!$bool) throw new \Exception('服务器处理数据失败');
                $arrSystemLogData = ['behavior' => '编辑角色指定字段', 'operationBefore' => $arrOperationBefore, 'operationAfter' => $arrSet, 'whereData' => $arrWhere];
                setSystemLog($arrSystemLogData);
                return callbackParam(0, true, [], '编辑成功');
        }

        /**
         * 删除角色
         * @param string $roleId
         * @return array
         * @throws \Exception
         */
        public static function delete(string $roleId): array
        {
                $arrOperationBefore = self::query($roleId)['data'];
                if (!$arrOperationBefore) throw new \Exception('数据不存在');
                $arrWhere = ['roleId' => strAddslashes($roleId)];
                $bool = SystemRole::remove($arrWhere);
                if (!$bool) throw new \Exception('服务器处理数据失败');
                $arrOperationBefore['permissions'] = SystemRolePermissions::getColumn($arrWhere, 'menuId');
                SystemRolePermissions::remove($arrWhere);
                $arrSystemLogData = ['behavior' => '删除角色', 'operationBefore' => $arrOperationBefore, 'whereData' => $arrWhere];
                setSystemLog($arrSystemLogData);
                return callbackParam(0, true, [], '删除成功');
        }

        /**
         * 分配权限
         * 揭示透露角色权限
         * @param string $roleId
         * @return array
         */
        public static function revealRolePermissions(string $roleId): array
        {
                #查出菜单权限信息供显示
                $arrWhere = ['status' => 1];
                $arrField = ['menuId', 'pid', 'name'];
                $arrOrderBy = ['sort' => 'DESC'];
                $arrMenu = SystemMenu::getAll($arrWhere, $arrField, $arrOrderBy);
                #查出该角色已分配的权限
                $arrWhere = ['roleId' => $roleId, ['pseudoChecked', '<>', 3]];
                $arrField = ['menuId', 'pseudoChecked'];
                $arrPermissions = SystemRolePermissions::getAll($arrWhere, $arrField);
                $arrResult = ['menu' => $arrMenu, 'permissions' => $arrPermissions];
                return callbackParam(0, true, $arrResult);
        }

        /**
         * 分配权限
         * 设置角色权限
         * @param string $roleId
         */
        public static function setRolePermissions(string $roleId): array
        {
                $arrPermissionsData = post('permissionsData');
                $arrWhere = ['roleId' => $roleId];
                $arrField = ['menuId', 'pseudoChecked'];
                $arrOperationBefore = SystemRolePermissions::getAll($arrWhere, $arrField);
                if ($arrOperationBefore) SystemRolePermissions::remove($arrWhere);
                $arrSet = [];
                $arrMenuId = array_column($arrPermissionsData, 'menuId');
                foreach ($arrPermissionsData as $k => $v) {
                        $arrSet[] = [
                                'roleId' => strAddslashes($roleId),
                                'menuId' => strAddslashes($v['menuId']),
                                'pseudoChecked' => intval($v['pseudoChecked'])
                        ];
                }
                if ($arrMenuId) {
                        $arrTempWhere = [['whereIn', 'menuId', $arrMenuId], ['reMenuId', '<>', '']];
                        $arrReMenuId = SystemMenu::getColumn($arrTempWhere, 'reMenuId');
                        $arrReMenuIdNew = [];
                        foreach ($arrReMenuId as $v) {
                                $arrReMenuIdNew = array_merge($arrReMenuIdNew, explode(',', $v));
                        }
                        $arrReMenuIdNew = array_unique($arrReMenuIdNew);
                        foreach ($arrReMenuIdNew as $v) {
                                if (in_array($v, $arrMenuId)) continue;
                                $arrSet[] = [
                                        'roleId' => strAddslashes($roleId),
                                        'menuId' => strAddslashes($v),
                                        'pseudoChecked' => 3
                                ];
                        }
                }
                if ($arrSet) SystemRolePermissions::insert($arrSet);
                $arrSystemLogData = ['behavior' => '分配角色权限', 'operationBefore' => $arrOperationBefore, 'operationAfter' => $arrSet, 'whereData' => $arrWhere];
                setSystemLog($arrSystemLogData);
                return callbackParam(0, true, [], '分配成功');
        }
}